const request = require('../../utils/request');

Page({
  data: {
    phone: '',
    smsCode: '',
    countdown: 0
  },

  onPhoneInput(e) {
    this.setData({ phone: e.detail.value });
  },

  onSmsCodeInput(e) {
    this.setData({ smsCode: e.detail.value });
  },

  // 获取短信验证码
  getSmsCode() {
    const phone = this.data.phone.trim();
    if (!phone || !/^1[3-9]\d{9}$/.test(phone)) {
      wx.showToast({ title: '请输入正确手机号', icon: 'none' });
      return;
    }

    if (this.data.countdown > 0) {
      return;
    }

    this.setData({ countdown: 60 });
    const timer = setInterval(() => {
      const value = this.data.countdown - 1;
      this.setData({ countdown: value });
      if (value <= 0) {
        clearInterval(timer);
      }
    }, 1000);

    request({
      url: '/api/auth/send-sms',
      method: 'POST',
      data: { phone }
    }).then((res) => {
      console.log('📱 绑定页发送验证码返回:', res);
      if (res.success) {
        wx.showToast({ title: '验证码已发送' });
      } else {
        wx.showToast({ title: res.message || '发送失败', icon: 'none' });
      }
    }).catch((err) => {
      console.error('发送验证码失败:', err);
      wx.showToast({ title: '网络错误', icon: 'none' });
    });
  },

  async bindPhone() {
    const phone = this.data.phone.trim();
    const smsCode = String(this.data.smsCode || '').trim();

    if (!phone || !/^1[3-9]\d{9}$/.test(phone)) {
      wx.showToast({ title: '请输入正确手机号', icon: 'none' });
      return;
    }

    if (!smsCode) {
      wx.showToast({ title: '请输入验证码', icon: 'none' });
      return;
    }

    const userId = wx.getStorageSync('userId');
    if (!userId) {
      wx.showToast({ title: '登录信息失效，请重新登录', icon: 'none' });
      wx.reLaunch({ url: '/pages/login/login' });
      return;
    }

    wx.showLoading({ title: '绑定中...' });
    try {
      const res = await request({
        url: '/api/auth/bind-phone-wechat',
        method: 'POST',
        data: { userId, phone, smsCode }
      });

      wx.hideLoading();
      if (res.success) {
        wx.showToast({ title: '绑定成功', icon: 'success' });

        // 后端可能进行了账号合并，这里使用返回的最终 userId 和 userInfo
        const mergedUserId = res.data?.userId || userId;
        const userInfo = res.data?.userInfo || {};

        // 更新本地缓存中的用户ID和用户信息
        wx.setStorageSync('userId', mergedUserId);
        wx.setStorageSync('userInfo', userInfo);

        const app = getApp();
        app.globalData.userId = mergedUserId;
        app.globalData.userInfo = userInfo;

        setTimeout(() => {
          wx.reLaunch({ url: '/pages/orderUser/orderUser' });
        }, 1200);
      } else {
        wx.showToast({ title: res.message || '绑定失败', icon: 'none' });
      }
    } catch (err) {
      wx.hideLoading();
      console.error('绑定手机号失败:', err);
      wx.showToast({ title: '网络错误', icon: 'none' });
    }
  }
});
